/**
 * @created by jiangcheng 2018-02-27
 * @updated by liujie yufp.config增加debug参数 2018-06-01
 * @description 全局配置入口
 */
(function (window, yufp) {
  function genUUID (len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],
        i;
    radix = radix || chars.length;

    if (len) {
      for (i = 0; i < len; i++) {
        uuid[i] = chars[0 | Math.random() * radix];
      }
    } else {
      var r;

      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';

      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
        }
      }
    }

    return uuid.join('');
  }

  var clientId = genUUID(16, 16) + Date.parse(new Date());
  var config = window.YUFP_SYS_CONFIG,
    debug = config.debugModel,
    mockModel = config.mockModel,
    webLogAble = config.webLogAble,
    langList = [];
  window.comLang = {};
  var l = window.localStorage.getItem('language');
  l && (l = l.substring(2), window.YUFP_SYS_CONFIG.language = l);
  yufp.config({
    // 别名配置
    alias: {
      'vue': './libs/vue/vue' + (debug ? '' : '.min') + '-2.5.13.js',
      'mock': './libs/mockjs/mock' + (debug ? '' : '.min') + '.js',
      'jquery': './libs/jquery/jquery' + (debug ? '' : '.min') + '.js',
      'echarts': './libs/echarts/echarts.min.js',
      'jsplumb': './libs/jsPlumb/jsPlumb-1.7.9.js'
    },
    charset: config.charset,
    version: config.version,
    debug: config.debugModel
  });

  // 前端组件语言文件加载
  langList = [
    './themes/lang/' + window.YUFP_SYS_CONFIG.language + '/common/component.js'];
  yufp.require.require(langList, function () {
    window.comLang = yufp.require.use(langList[0]).component;
  });

  // 首先加载，否则会出现菜单为NULL的情况
  if (config.multiLanguage) {
    yufp.require.require('./themes/lang/' + window.YUFP_SYS_CONFIG.language + '/common/menu.js');
    yufp.require.require('./themes/lang/' + window.YUFP_SYS_CONFIG.language + '/common/lookup.js');
  }

  // css依赖库
  var libsCss = [
    './libs/element-ui/index.css',
    './themes/common/icoFonts/icoFonts.css',
    './themes/common/iconfont/iconfont.css',
    './themes/common/common.css',
    './themes/common/oca.css',
    './themes/' + config.theme + '/main.css',
    './custom/widgets/css/bus.css'
  ];

  // js依赖库
  var libsJs = [
    'vue',
    'jquery',
    './libs/polyfill/es6-promise.auto.min.js',
    './libs/element-ui/index.js',
    './libs/echarts/echarts.min.js',
    './custom/common/app.data.service.js',
    './custom/plugins/yufp.settings.js',
    './custom/plugins/yufp.language.js',
    './custom/plugins/yufp.localstorage.js',
    './custom/plugins/yufp.sessionstorage.js',
    './custom/plugins/yufp.service.js',
    './custom/plugins/yufp.validator.js',
    './custom/plugins/yufp.util.js',
    './custom/plugins/yufp.lookup.js',
    './custom/plugins/yufp.session.js',
    './custom/plugins/yufp.frame.js',
    './custom/plugins/yufp.messagelookup.js',
    './libs/fullscreen/screenfull.min.js', // 全屏操作插件
    './custom/common/app.js',
    // 使用静态菜单
    './custom/common/app.data.menu.js',
    './libs/jsencrypt/jsencrypt.min.js'
  ];
  // 路由表
  var routeTables = [
    './custom/route-tables/route.common.js',
    './custom/route-tables/route.echain.js'
  ];

  // 合并lib
  var libs = libsCss.concat(libsJs, routeTables);
  yufp.require.use(libs).done(function () {
    // yufp别名
    window.yu = window.yufp;
    // 设置配置
    yufp.settings.config(config);
    // mock加载
    if (mockModel) {
      yufp.require.require('./mocks/index.js');
    }
    // 监控模式时，引入监控文件
    if (webLogAble) {
      // 监控需要增加tfp 指纹信息
      yufp.require.require('custom/plugins/yufp.tfp.js');
      yufp.require.require('custom/plugins/yufp.monitor.js');
    }
    // 多语言加载
    window.YUFP_SYS_CONFIG.language = yufp.localStorage.get('language') || window.YUFP_SYS_CONFIG.language;
    yufp.require.require('./libs/vuei18n/vue-i18n.js');
    // 1、框架及自定义组件语言文件加载
    yufp.require.use('./themes/lang/' + window.YUFP_SYS_CONFIG.language + '/common/widget.js');
    yufp.require.use('./themes/lang/' + window.YUFP_SYS_CONFIG.language + '/common/menu.js');
    yufp.require.use('./themes/lang/' + window.YUFP_SYS_CONFIG.language + '/common/yuwp.js');
    // 2、逻辑系统、菜单、字典项、提示消息语言文件加载
    if (config.multiLanguage) {
      var languageList = yufp.clone(yufp.frame.baseFrameOptions.languageList, []);
      var languageLibs = [];
      // 循环遍历，添加公共语言文件。
      for (var i = 0; i < languageList.length; i++) {
        var element = languageList[i];
        if (element.id === window.YUFP_SYS_CONFIG.language) {
          languageLibs.push('./themes/lang/' + element.id + '/index.js');
        }
      }
      if (languageLibs.length > 0) {
        yufp.require.require(languageLibs, function () {
          // 将公共加载的主js加载完成后，再加载各项子资源
          yufp.require.use(window.commonLanguage).done(function () {
            window.commonLanguage = null;
            var locate = {};
            for (var i = 0; i < languageList.length; i++) {
              var element = languageList[i];
              yufp.extend(locate, window['global_' + element.id]);
            }
            Vue.config.locate = locate;
          });
        });
      }
    }
    // 紧凑模式
    if (config.compactMode) {
      yufp.require.require('./themes/common/compact.css');
    }
    // 加入请求过滤器
    yufp.service.addFilter({
      // 过滤器名称
      name: 'messageParser',
      // 请求前触发
      before: function (event) {
        // 定义请求头
        var headers = {};
        // 定义请求数据
        var reqData = {
          // 请求头
          headers: headers,
          // 请求数据
          data: event.data
        };
        // 保存导出数据
        event.code = 0;
        event.data = reqData;
        // 返回处理标志，true则继续处理，false则中断处理
        return true;
      },

      // 数据返回后触发
      after: function (event) {
        // 只处理JSON对象
        if (yufp.type(event.data) == 'object' && yufp.type(event.data.header) != 'undefined') {
          // 获取响应头
          var rspHeader = event.data.header;
          // 获取响应数据
          var rspData = event.data.data;

          if (yufp.type(rspHeader.code) == 'undefined' || rspHeader.code == 0) {
            // 保存导出数据
            event.code = 0;
            event.message = '';
            event.data = rspData;
            // 返回处理标志，true则继续处理，false则中断处理
            return true;
          } else {
            // 保存导出数据
            event.code = rspHeader.code;
            event.message = rspHeader.msg;
            event.data = rspData;
            // 返回处理标志，true则继续处理，false则中断处理
            return true;
          }
        }

        // 返回处理标志，true则继续处理，false则中断处理
        return true;
      },
      // HTTP请求异常
      exception: function (event) {
        var status = event.xhr.status;
        var flag = true;
        var globalVm = yufp.util.globalVm;
        switch (status) {
        case 401:
          var responseUrl = event.requestUrl;
          // 服务平台坑（/api/logout注销会在请求头带token，若token已过期，也会走到此处)
          if (responseUrl.indexOf(yufp.session.settings.logoutUrl) < 0) {
            // 判断非注销服务造成的401，才走此逻辑
            yufp.session.logout(true);
          }
          flag = false;
          break;
        case 403:
          globalVm.$message({
            message: window.comLang.SysMsg_001,
            type: 'warning'
          });
          flag = false;
          break;
        case 404:
          globalVm.$message({
            message: window.comLang.SysMsg_002,
            type: 'error'
          });
          flag = false;
          break;
        default:
          globalVm.$message({
            message: window.comLang.SysMsg_002,
            type: 'error'
          });
          flag = false;
          break;
        }
        return flag;
      }
    });

    // 设置默认root id
    yufp.router.setDefaultRootId(config.defaultRootId);
    // 加入路由过滤器
    yufp.router.addFilter({

      /**
       * 过滤器名称
       */
      name: 'default',

      /**
       * 路由跳转前执行
       * @param code
       * @param cite
       */
      before: function (code, data, cite) {
        if (window.YUFP_SYS_CONFIG.sugoModel && typeof window.sugoio != 'undefined') {
          var sugoLoad = window.sugoio.load;
          cite.options && cite.options.title ? sugoLoad && sugoLoad(code, cite.options) : '';
        }
        var route;
        if (config.debugModel) {
          route = yufp.router.getRoute(code) || {};
          yufp.logger.info('【Router-JS】【' + code + '】: ' + route.js);
        }
        // 多语言标志位true 时才设置前缀--取消默认加载页面语言文件 update by liucheng3 2019-12-26
        // if (config.multiLanguage) {
        //   route = yufp.router.getRoute(code) || {};
        //   var prefix = route.js.substring(0, route.js.lastIndexOf('.'));
        //   var languageList = yufp.clone(yufp.frame.language, []);
        //   // 循环遍历，添加页面名称相同的带语言类型后缀的js语言文件
        //   for (var i = 0; i < languageList.length; i++) {
        //     var element = languageList[i];
        //     if (element.mapping === window.YUFP_SYS_CONFIG.language || element.id === window.YUFP_SYS_CONFIG.language) {
        //       if (element.mapping) {
        //         yufp.require.require('./themes/lang/' + element.mapping + '/' + prefix + '.js');
        //       } else {
        //         yufp.require.require('./themes/lang/' + element.id + '/' + prefix + '.js');
        //       }
        //     }
        //   }
        //   cite.prefix = code;
        // }
        // 增加默认主题标志
        var dom = document.querySelector('.yu-frame-body');
        var classname = dom.getAttribute('class');
        if (classname.indexOf(config.theme) === -1) {
          classname = classname + ' ' + config.theme;
          dom.setAttribute('class', classname);
        }
        return true;
      },

      /**
       * 加载路由内容前执行
       * @param code
       * @param cite
       */
      mount: function (code, cite) { },

      /**
       * ready函数执行
       * @param exports
       * @param code
       * @param data
       * @param cite
       */
      ready: function (exports, code, data, cite) { },

      /**
       * 卸载路由内容前执行
       * @param code
       * @param cite
       */
      unMount: function (code, cite) {
        if (window.YUFP_SYS_CONFIG.sugoModel && typeof window.sugoio != 'undefined') {
          var sugoUnLoad = window.sugoio.unload;
          cite.options && cite.options.title ? sugoUnLoad && sugoUnLoad(code, cite.options) : '';
        }
      },

      /**
       * destroy函数执行
       * @param exports
       * @param code
       * @param cite
       */
      destroy: function (exports, code, cite) { }
    });

    var encodePassword = function (pwd) {
      var encrypt = new window.JSEncrypt();
      encrypt.setPublicKey(yufp.util.getRSAPublicKey());
      var encryptPwd = encrypt.encrypt(pwd);
      var encodePwd = encodeURIComponent(encryptPwd);
      return encodePwd;
    };

    var login = function (data, route, delay) {
      var globalVm = yufp.util.globalVm;
      if (data.hasOwnProperty('SSO_USER_TOKEN')) {
        var headers2 = {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          'Authorization': 'Basic d2ViX2FwcDo='
        };
        yufp.service.request({
          needToken: false,
          url: backend.msmFrontWebService + '/api/sznshauth/checktoken',
          method: 'get',
          headers: headers2,
          data: data,
          callback: function (code, message, response) {
            if (response.code == '0') {
              var data2 = {
                username: response.data.username,
                password: encodePassword(response.data.password),
                'grant_type': 'password',
                passwordType: '2',
                sysId: this.sysLogicId,
                clientId:clientId
              };
              yufp.service.request({
                needToken: false,
                url: backend.uaaService + '/oauth/token',
                method: 'post',
                headers: headers2,
                data: data2,
                callback: function (code, message, response) {
                  if (response && response.access_token && !response.code) {
                    yufp.service.putToken({
                      'access_token': response.access_token,
                      'refresh_token': response.refresh_token,
                      'expires_in': response.expires_in
                    });
                    yufp.session.loadUserSession(function () {
                      let integralCode = '12';
                      yufp.util.addIntegral(integralCode)
                      window.location.href = location.href.substring(0, location.href.indexOf('?'));
                    });
                  }
                }
              });
            } else {
              // if (response.code == '5000') {
              //   globalVm.$message({
              //     message: response.message,
              //     type: 'error'
              //   });
              // }
              // yufp.session.logout();
              // location.href = location.href.substring(0, location.href.indexOf('?'));
              // 主页入口
              // setTimeout(function () {
              //   yufp.session.logout(function () {
              //     if (route != config.startPage) {
              //       route = config.startPage;
              //     }
              //     yufp.router.to(route, data);
              //   }, delay);
              // });
              // data = {};
              if (response.code == '5000') {
                globalVm.$message({
                  message: response.message,
                  type: 'error'
                });
              }
              setTimeout(function () {
                location.href = location.href.substring(0, location.href.indexOf('?'));
              },2000)
              // yufp.session.logout(function () {
              //   yufp.router.to(route, data);
              // });
            }
          }
        });
      } else {
        // 主页入口
        // setTimeout(function () {
        //   yufp.router.to(route, data);
        // }, delay);
        if (yufp.session.getCurrentRoute() == 'frame') {
          setTimeout(function () {
            yufp.session.loadUserSession(function () {
              yufp.router.to(route, data);
            });
          }, delay);
        } else {
          setTimeout(function () {
            yufp.router.to(route, data);
          }, delay);
        }
      }
    };

    /**
     * 创建hash处理事件
     */
    var hashFn = function () {
      var hash = location.hash ? location.hash : '';
      var data = {}; // 路由参数
      var route = config.startPage; // 启动路由
      var currRoute = yufp.session.getCurrentRoute();
      route = currRoute || route;
      var sIndex = hash.indexOf('!'),
        eIndex = hash.indexOf('?');
      if (sIndex != -1) {
        route = eIndex != -1 ? hash.substring(sIndex + 1, eIndex) : hash.slice(sIndex + 1);
      }
      data = yufp.urlParam2Object(location.search); // 问号参数转换
      if (eIndex != -1 && hash.slice(eIndex + 1)) {
        yufp.extend(data, yufp.urlParam2Object(hash.slice(eIndex))); // hash参数转换, 并合并至data路由参数中
      }

      // yufp.logger.info('触发hash事件,hash:' + hash);
      // 调试模式true时，有mocks请求，故延迟加载
      var delay = mockModel ? 500 : 100;
      if (data.debug && route.indexOf('%2F')) {
        // IDE 预览入口
        var idePreview = 'idePreview',
          url = decodeURIComponent(route);
        route = 'frame';
        var t = new Date().getTime();
        yufp.router.addRoute(idePreview, {
          html: url + '.html?t=' + t,
          js: url + '.js?t=' + t
        });
        setTimeout(function () {
          // mock & debug模式，token不存在情况下，允许临时塞一个假token以实现模拟预览
          if (config.debugModel && !yufp.service.getToken()) {
            var suffix = new Date().getTime();
            yufp.service.putToken({
              'access_token': 'Basicd2ViX2FwcDo=' + suffix,
              'expires_in': 600, // 单位：秒
              'refresh_token': 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9' + suffix
            });
          }
          yufp.session.loadUserSession(function () {
            yufp.router.to(route, data);
            setTimeout(function () {
              yufp.frame.addTab({
                id: idePreview, // 菜单功能ID（路由ID）
                key: 'custom_' + t, // 自定义唯一页签key,请统一使用custom_前缀开头
                title: window.comLang.IDE_preview, // 页签名称
                data: data
              });
            }, 500);
          });
        }, delay);
      } else if (route == config.startPage  || route == 'frame') {
        // 主页入口
        // setTimeout(function () {
        //   yufp.router.to(route, data);
        // }, delay);
        login(data, route, delay);
      } else {
        setTimeout(function () {
          yufp.session.loadUserSession(function () {
            yufp.router.to(route, data);
          });
        }, delay);
      }
      // 多语言title翻译
    };
    // 添加hash change事件 @modify by luyq1@2020-04-14解决IE刷新后内存不断增长(释放监听)
    if (window.addEventListener) {
      window.removeEventListener('hashchange', hashFn, false);
      window.addEventListener('hashchange', hashFn, false);
    } else if (window.attachEvent) {
      window.detachEvent('on' + 'hashchange', hashFn);
      window.attachEvent('on' + 'hashchange', hashFn);
    } else {
      window['onhashchange'] = hashFn;
    }
    // 页面跳转
    hashFn();
  });
}(window, yufp));